package com.service.impl;

import com.dao.impl.BookDaoImpl;
import com.dao.impl.OrderDaoImpl;
import com.dao.impl.OrderItemDaoImpl;
import com.javabean.*;
import com.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class OrderServiceImpl implements OrderService {
    OrderDaoImpl a = new OrderDaoImpl();
    OrderItemDaoImpl b = new OrderItemDaoImpl();
    BookDaoImpl c = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        //生成订单号 唯一性
        String orderid = System.currentTimeMillis() + "" + userId;
        Order order = new Order(orderid, new Date(), cart.getTotalprice(), 0, userId);
        a.saveOrder(order);
        //遍历购物车中每一个商品项转化成为订单项
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            //获取购物车中的商品项
            CartItem cartItem = entry.getValue();
            //转换为订单项
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalprice(), orderid);
            b.saveOrderItem(orderItem);
            //更新库存和销量
            Book book = c.queryBookById(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            c.updateBook(book);
        }
        cart.clear();
        return orderid;
    }

    @Override
    public List<Order> showAllOrders() {
        return a.queryOrders();
    }

    @Override
    public int sendOrder(String orderid) {
        return a.changeOrderStatus(orderid, 1);
    }

    @Override
    public List<OrderItem> showOrderDetail(String orderid) {
        return b.queryOrderItemsByOrderId(orderid);
    }

    @Override
    public List<Order> showMyOrders(Integer userid) {
        return a.queryOrdersByUserId(userid);
    }

    @Override
    public int receiveOrder(String orderid) {
        return a.changeOrderStatus(orderid, 2);
    }
}
